#include "ParticleSystem.h"
#ifdef WIN32
#include "OpenGLExt.h"
#else
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#endif
#include <algorithm>

float fRand(float fMin, float fMax)
{
    float f = (float)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}
void Firework::Create()
{
	glGenBuffers(1, &vboID);
	InitData();
}

#define  Pr  .299
#define  Pg  .587
#define  Pb  .114

void changeSaturation(float *R, float *G, float *B, float change) {

  float  P=sqrt(
  (*R)*(*R)*Pr+
  (*G)*(*G)*Pg+
  (*B)*(*B)*Pb ) ;

  *R=max(0.0f, min(1.0, P+((*R)-P)*change));
  *G=max(0.0f, min(1.0, P+((*G)-P)*change));
  *B=max(0.0f, min(1.0, P+((*B)-P)*change));
}
void Firework::InitData()
{
	time = fRand(-2.0f, 0.0f);
	center.x = fRand(-8.0f, 8.0f);
	center.y = fRand(-5.0f, 5.0f);
	center.z = fRand(-5.0f, 5.0f);
	color.x = fRand(0.0f, 1.0f);
	color.y = fRand(0.0f, 1.0f);
	color.z = fRand(0.0f, 1.0f);
	changeSaturation(&color.x, &color.y, &color.z, 2.0);
	int size = FIREWORK_PARTICLE_COUNT*9*6;
	float *buffer = new float[size];
	for(int i = 0; i<FIREWORK_PARTICLE_COUNT;i++)
	{
		float size = fRand(0.2f, 0.3f);
		Vector3f direction;
		direction.x = fRand(-1.0f, 1.0f);
		direction.y = fRand(-1.0f, 1.0f);
		direction.z = fRand(-1.0f, 1.0f);
		direction = Normalize(direction)*5.0f;
		float speed = 5.0f;//fRand(3.0f, 5.0f);
		float* pointer = buffer + i*9*6;
		pointer[0] = - size; //upper left
		pointer[1] = + size;
		pointer[2] = 0.0f;
		pointer[3] = 0.0f;
		pointer[4] = 0.0f;
		
		pointer[9] = + size; //bottom right
		pointer[10] = - size;
		pointer[11] = 0.0f;
		pointer[12] = 1.0f;
		pointer[13] = 1.0f;

		pointer[18] = + size; //upper right
		pointer[19] = + size;
		pointer[20] = 0.0f;
		pointer[21] = 1.0f;
		pointer[22] = 0.0f;

		pointer[27] = - size; //upper left
		pointer[28] = + size;
		pointer[29] = 0.0f;
		pointer[30] = 0.0f;
		pointer[31] = 0.0f;

		pointer[36] = - size; //bottom left
		pointer[37] = - size;
		pointer[38] = 0.0f;
		pointer[39] = 0.0f;
		pointer[40] = 1.0f;

		pointer[45] = + size; //bottom right
		pointer[46] = - size;
		pointer[47] = 0.0f;
		pointer[48] = 1.0f;
		pointer[49] = 1.0f;
		
		for(int j = 0;j<6;j++)
		{
			pointer[j*9 + 5] = direction.x;
			pointer[j*9 + 6] = direction.y;
			pointer[j*9 + 7] = direction.z;
			pointer[j*9 + 8] = speed;
		}

	}

	glBindBuffer(GL_ARRAY_BUFFER, vboID );	
	glBufferData(GL_ARRAY_BUFFER, size*sizeof(float), buffer, GL_STATIC_DRAW );

	delete[] buffer;
}
void Firework::Release()
{
	glDeleteBuffers(1, &vboID);
}
void Firework::Update(long timeElapsed)
{
	time += float(timeElapsed)/1000.0f;
	if(time > 5.0f)
	{
		InitData();
	}
}